<template>
  <div class="app-container">
    <!--展示生成的代码-->
    <el-dialog :visible.sync="visible" :close-on-click-modal="false" fullscreen width="80%" height="100%" append-to-body>
      <template v-slot:title>
        <div class="el-dialog__header">
          <span>代码展示</span>
          <el-button type="primary" icon="el-icon-download" style="margin-left: 20px;" @click="handleDownload">
            下载
          </el-button>
        </div>
      </template>
      <el-tabs type="border-card">
        <el-tab-pane v-for="(value, key) in tabData" :key="key" :label="key">
          <editor :value="value" :options="options" :lang="lang" theme="chrome" width="100%" height="600px" @init="editorInit" />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import { handleDownload } from './api'
import waves from '@/directive/waves'

export default {
  // 当前页面名称（组件）
  name: 'CodeView',
  // 引用组件
  components: {
    editor: require('vue2-ace-editor')
  },
  directives: { waves },
  filters: {},
  // props属性
  props: {
    codeViewParams: {
      type: Object,
      require: true,
      default: undefined
    }
  },
  data() {
    return {
      // 是否显示弹出层
      visible: false,
      // 支持语言
      lang: 'java', // html、javascript
      // 展示内容
      content: '',
      // 数据对象
      tabData: [],
      // 配置项
      options: {
        wrap: true, // 换行
        enableLiveAutocompletion: true, // 智能补全
        enableSnippets: true, // 启用代码段
        readOnly: true
      }
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    init() {
      this.visible = this.codeViewParams.visible
      this.tabData = this.codeViewParams.tabData
    },
    editorInit() {
      require('brace/ext/language_tools')
      require('brace/mode/html')
      require('brace/mode/javascript')
      require('brace/mode/less')
      require('brace/mode/java')
      require('brace/theme/chrome')
      require('brace/snippets/javascript')
      require('brace/snippets/java')
    },
    // 下载代码
    async handleDownload() {
      const res = await handleDownload()
      const blob = new Blob([res])
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = 'src.zip'
      document.body.appendChild(link)
      link.click()
      link.remove()
    }
  }
}
</script>

<style>
.el-dialog__header {
  /* 使用 flex 布局 */
  display: flex;
  /* 子元素在主轴上两端对齐 */
  justify-content: space-between;
  /* 子元素在交叉轴上居中对齐 */
  align-items: center;
}
</style>
